﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;

namespace CallCenter.Common
{
    public class JsonHelperEx
    {
        public JsonHelperEx()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        /// <summary>
        /// 把JSON字符串还原为对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="szJson">JSON字符串</param>
        /// <returns>对象实体</returns>
        public static T ParseFormJson<T>(string szJson)
        {
            try
            {
                T obj = Activator.CreateInstance<T>();
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
                {
                    DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
                    return (T)dcj.ReadObject(ms);
                }
            }
            catch (Exception ex)
            {
                NLogger.GetInstance().Error(szJson + "：" + ex.ToString());
            }

            return default(T);
        }

        /// <summary>  
        /// 过滤特殊字符
        /// </summary>  
        /// <param name="strParam"></param>  
        /// <returns></returns>  
        public static string String2Json(String strParam)
        {
            if(string.IsNullOrEmpty(strParam))
            {
                return null;
            }

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < strParam.Length; i++)
            {
                char c = strParam.ToCharArray()[i];
                switch (c)
                {
                    case '\"':
                        sb.Append("\\\""); break;
                    case '\\':
                        sb.Append("\\\\"); break;
                    case '/':
                        sb.Append("\\/"); break;
                    case '\b':
                        sb.Append("\\b"); break;
                    case '\f':
                        sb.Append("\\f"); break;
                    case '\n':
                        sb.Append("\\n"); break;
                    case '\r':
                        sb.Append("\\r"); break;
                    case '\t':
                        sb.Append("\\t"); break;
                    case '\v':
                        sb.Append("\\v"); break;
                    case '\0':
                        sb.Append("\\0"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }

        #region 对象类型序列化为json 字符
        /// <summary>
        /// 对象类型序列化为json 字符
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="jsonObject">待转换实体</param>
        /// <param name="encoding">编码格式</param>
        /// <returns>string</returns>
        public static string ObjectToJson<T>(Object jsonObject, Encoding encoding)
        {
            string result = String.Empty;
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                serializer.WriteObject(ms, jsonObject);
                result = encoding.GetString(ms.ToArray());
            }
            return result;
        }
        #endregion

        #region json字符反序列化为对象

        /// <summary>
        /// json字符反序列化为对象
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="json">json字符串</param>
        /// <param name="encoding">编码格式</param>
        /// <returns>T</returns>
        public static T JsonToObject<T>(string json, Encoding encoding)
        {
            T resultObject = default(T);
            try
            {
                resultObject = Activator.CreateInstance<T>();
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(encoding.GetBytes(json)))
                {
                    resultObject = (T)serializer.ReadObject(ms);
                }
            }
            catch
            {
                NLogger.GetInstance().Error("解析Json字符串失败。");
            }

            return resultObject;
        }

        #endregion

    }
}
